//
//  JiaYuanEncrypt.m
//  Yuan
//
//  Created by Sang HsiuJane on 7/5/11.
//  Copyright 2011 JiaYuan. All rights reserved.
//

#import "JiaYuanEncrypt.h"
#import <CommonCrypto/CommonDigest.h>
#import <CommonCrypto/CommonCryptor.h>
#include <sys/types.h>
#include <sys/sysctl.h>
// #import "ShareData.h"
#import "NSData+Base64.h"
#import <UIKit/UIKit.h>
// #import "Base64.h"


@implementation JiaYuanEncrypt

//+(NSString *)hashedISU {
//    NSString *result = nil;
//   // NSString *isu = [UIDevice currentDevice].uniqueIdentifier;
//    NSString *isu=[[ShareData sharedInstance]deviceID];
//    if(isu) {
//        unsigned char digest[16];
//        NSData *data = [isu dataUsingEncoding:NSASCIIStringEncoding];
//        CC_MD5([data bytes], [data length], digest);
//        
//        result = [NSString stringWithFormat: @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
//                  digest[0], digest[1], 
//                  digest[2], digest[3],
//                  digest[4], digest[5],
//                  digest[6], digest[7],
//                  digest[8], digest[9],
//                  digest[10], digest[11],
//                  digest[12], digest[13],
//                  digest[14], digest[15]];
//        result = [result uppercaseString];
//    }
//    return result;
//}

+ (NSString *)md5:(NSString *)str
{
	const char *cStr = [str UTF8String];
	unsigned char result[CC_MD5_DIGEST_LENGTH];
	CC_MD5( cStr, (CC_LONG)strlen(cStr), result );
	return [NSString 
			stringWithFormat: @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
			result[0], result[1],
			result[2], result[3],
			result[4], result[5],
			result[6], result[7],
			result[8], result[9],
			result[10], result[11],
			result[12], result[13],
			result[14], result[15]
			];
	
}


+ (NSString*)md5Hash:(NSData *)data {
	unsigned char result[CC_MD5_DIGEST_LENGTH];
	CC_MD5([data bytes], (CC_LONG)[data length], result);
	
	return [NSString stringWithFormat:
			@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
			result[0], result[1], result[2], result[3], result[4], result[5], result[6], result[7],
			result[8], result[9], result[10], result[11], result[12], result[13], result[14], result[15]
			];
}

+ (NSString*)sha1Hash:(NSData *)data {
	unsigned char result[CC_SHA1_DIGEST_LENGTH];
	CC_SHA1([data bytes], (CC_LONG)[data length], result);
	
	return [NSString stringWithFormat:
			@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
			result[0], result[1], result[2], result[3], result[4], result[5], result[6], result[7],
			result[8], result[9], result[10], result[11], result[12], result[13], result[14], result[15],
			result[16], result[17], result[18], result[19]
			];
}

+ (NSData *)AES256EncryptWithKey:(NSData *)data key:(NSString *)key {
    
    NSData *returnData = nil;
    
    char keyPtr[kCCKeySizeAES256+1];
    bzero(keyPtr, sizeof(keyPtr));
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
    
    NSUInteger dataLength = [data length];
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    
    size_t numBytesEncrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128,
                                          kCCOptionPKCS7Padding | kCCOptionECBMode,
                                          keyPtr, kCCBlockSizeAES128,
                                          NULL,
                                          [data bytes], dataLength,
                                          buffer, bufferSize,
                                          &numBytesEncrypted);
    
    if (cryptStatus == kCCSuccess) {
        returnData  = [[NSData alloc] initWithBytes:buffer length:numBytesEncrypted];
    }
    
    free(buffer);
    
    return returnData;
}

+ (NSData *)AES256DecryptWithKey:(NSData *)data key:(NSString *)key {
    
    NSData *returnData = nil;
    
    char keyPtr[kCCKeySizeAES256+1];
    bzero(keyPtr, sizeof(keyPtr));
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
    
    NSUInteger dataLength = [data length];
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    
    size_t numBytesDecrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128,
                                          kCCOptionPKCS7Padding | kCCOptionECBMode,
                                          keyPtr, kCCBlockSizeAES128,
                                          NULL,
                                          [data bytes], dataLength,
                                          buffer, bufferSize,
                                          &numBytesDecrypted);
    
    if (cryptStatus == kCCSuccess) {
        returnData  = [[NSData alloc] initWithBytes:buffer length:numBytesDecrypted];
    }
    
    
    free(buffer);
    
    return returnData;
}

+(NSString *)AES128Encrypt:(NSString *)plainText key:(NSString *)key
{
    NSData *resultData = nil;
    char keyPtr[kCCKeySizeAES128+1];
    memset(keyPtr, 0, sizeof(keyPtr));
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
    
    NSData* data = [plainText dataUsingEncoding:NSUTF8StringEncoding];
    NSUInteger dataLength = [data length];
    
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    size_t numBytesEncrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
                                          kCCAlgorithmAES128,
                                          kCCOptionPKCS7Padding | kCCOptionECBMode,
                                          keyPtr,
                                          kCCBlockSizeAES128,
                                          NULL,
                                          [data bytes],
                                          dataLength,
                                          buffer,
                                          bufferSize,
                                          &numBytesEncrypted);
    if (cryptStatus == kCCSuccess) {
        // resultData = [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
        resultData = [[NSData alloc] initWithBytes:buffer length:numBytesEncrypted];
    }
    free(buffer);
    // return [Base64 stringByEncodingData:resultData];
    return [self hexStringFromData:resultData];
}

+(NSString *)AES128Decrypt:(NSString *)encryptText key:(NSString *)key
{
    NSData *resultData = nil;
    char keyPtr[kCCKeySizeAES128 + 1];
    memset(keyPtr, 0, sizeof(keyPtr));
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
    
    // NSData *data = [Base64 decodeData:[encryptText dataUsingEncoding:NSUTF8StringEncoding]];
    // encryptText = [self stringFromHexString:encryptText];
    NSData *data = [NSData dataFromBase64String:encryptText];
    
    NSUInteger dataLength = [data length];
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    
    size_t numBytesCrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt,
                                          kCCAlgorithmAES128,
                                          kCCOptionPKCS7Padding,
                                          keyPtr,
                                          kCCBlockSizeAES128,
                                          NULL,
                                          [data bytes],
                                          dataLength,
                                          buffer,
                                          bufferSize,
                                          &numBytesCrypted);
    if (cryptStatus == kCCSuccess) {
        // resultData = [NSData dataWithBytesNoCopy:buffer length:numBytesCrypted];
        resultData = [[NSData alloc] initWithBytes:buffer length:numBytesCrypted];
        
    }
    free(buffer);
    return [[NSString alloc] initWithData:resultData encoding:NSUTF8StringEncoding];
}

// 十六进制转换为普通字符串的。
+ (NSString *)stringFromHexString:(NSString *)hexString { //
    
    char *myBuffer = (char *)malloc((int)[hexString length] / 2 + 1);
    bzero(myBuffer, [hexString length] / 2 + 1);
    for (int i = 0; i < [hexString length] - 1; i += 2) {
        unsigned int anInt;
        NSString * hexCharStr = [hexString substringWithRange:NSMakeRange(i, 2)];
        NSScanner * scanner = [[NSScanner alloc] initWithString:hexCharStr];
        [scanner scanHexInt:&anInt];
        myBuffer[i / 2] = (char)anInt;
    }
    NSString *unicodeString = [NSString stringWithCString:myBuffer encoding:4];
    return unicodeString;
    
    
}

// 普通字符串转换为十六进

+ (NSString *)hexStringFromData:(NSData *)data {
    Byte *bytes = (Byte *)[data bytes];
    // 下面是Byte 转换为16进制。
    NSString *hexStr = @"";
    for(int i=0; i<[data length]; i++) {
        NSString *newHexStr = [NSString stringWithFormat:@"%x",bytes[i]& 0xff]; //16进制数
        newHexStr = [newHexStr uppercaseString];
        
        if([newHexStr length] == 1) {
            newHexStr = [NSString stringWithFormat:@"0%@",newHexStr];
        }
        
        hexStr = [hexStr stringByAppendingString:newHexStr];
       
    } 
    return hexStr; 
}


/*
 // 判断当前设备类型
 iPhone Simulator == i386
 iPhone == iPhone1,1
 3G iPhone == iPhone1,2
 3GS iPhone == iPhone2,1
 4 iPhone == iPhone3,1
 
 1st Gen iPod == iPod1,1
 2nd Gen iPod == iPod2,1
 3rd Gen iPod == iPod3,1
 4rd gen ipod == iPod4,1
 */
+ (NSString *)currentMachine {
	
	size_t size;
	sysctlbyname("hw.machine", NULL, &size, NULL, 0); 
	
	// Allocate the space to store name
	char *name = malloc(size);
	// Get the platform name
	sysctlbyname("hw.machine", name, &size, NULL, 0);
	// Place name into a string
	NSString *machine = [NSString stringWithUTF8String:name];
	// Done with this
	free(name);
	return machine;
	
}

+ (BOOL)isJailbreak{

    NSURL* url = [NSURL URLWithString:@"cydia://package/com.example.package"];
    return [[UIApplication sharedApplication] canOpenURL:url];
//    BOOL jail = NO;
//    FILE *f = fopen("/bin/ssh", "r");
//    if (f!=NULL) {
//        //pirated! now what do we do?
//        jail = YES;
//    }
//    fclose(f);
//    
//    NSString *filePath = @"/Applications/Cydia.app";
//    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath])
//    {
//        // do something useful
//        jail = YES;
//    }
//    return jail;
}

+ (NSString *)jbParam
{
    NSString *param = @"0";
    if ([self isJailbreak])
    {
        param = @"1";
    }
    return param;
}
    
@end
